import React, { useEffect, useState } from 'react';
import { renewPosition } from '@/redux/actions';
import store from '@/redux/store.js';
import type { MenuProps } from 'antd';
import { Button,Dropdown, Space,message,Popover, ConfigProvider,Modal   } from 'antd';
import { MoreOutlined,StarTwoTone,DeleteOutlined,DownOutlined,CloseOutlined, LockOutlined, QuestionCircleOutlined, UnlockOutlined } from '@ant-design/icons';
const BarChartLazy = React.lazy(() => import('@/pages/Dashboard/component/barGridLayout'));
const PieChartLazy = React.lazy(() => import('@/pages/Dashboard/component/pieGridLayout'));
import { Layout, Responsive, WidthProvider } from 'react-grid-layout';
const ResponsiveReactGridLayout = WidthProvider(Responsive);

import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import './index.less';

interface DashboardWidgetInfo {
  widgetName: string;
  layout: Layout;
}
function Dashboard() {
  let [layoutData, setLayoutData] = useState([]);
  let [pageHeight, setPageHeight] = useState(document.body.offsetHeight - 100);
  let [checkItem, setCheckItem] = useState('')
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const getData = () => {
    return new Promise((resolve, reject) => {
      let data = [
        { i: 'a', x: 0, y: 0, w: 6, h: 2, chartType: 'pie',static:false,oprates:['del','sd'],popShow:false, },
        { i: 'b', x: 6, y: 0, w: 6, h: 2, chartType: 'bar',static:false,oprates:['del','sd'],popShow:false, },
        { i: 'c', x: 0, y: 2, w: 6, h: 2, chartType: 'bar',static:false,oprates:['del','sd'],popShow:false, },
        { i: 'd', x: 6, y: 2, w: 6, h: 2, chartType: 'bar',static:false,oprates:['del','sd'],popShow:false, },
      ];
      resolve(data);
    });
  };
  useEffect(() => {
    getData().then((res) => {
      setLayoutData(res);
      store.dispatch(renewPosition(res));
    });
    return ()=>{
      store.dispatch(renewPosition(layoutData));
    }
  }, []);

  const onMouseLeave = (e,val) => {
    if(!open){
      setCheckItem('')
    }
  }
  const onMousEenter=(e,val) => {
    setCheckItem(val.i)
  }
  const lockItem = (e,val,index)=>{
    let newLayOutData = layoutData.map((item)=>{
      if(item.i == val.i){
        item.static = true
      }
      return item
    })
    setLayoutData(newLayOutData)
  }
  const unLockItem = (e,val,index)=>{
    let newLayOutData = layoutData.map((item)=>{
      if(item.i == val.i){
        item.static = false
      }
      return item
    })
    setLayoutData(newLayOutData)
  }
  const onRemoveItem = (e,val,index)=>{
    setOpen(true);
  }
  const handleOk = () => {
    setConfirmLoading(false);
    setOpen(false);
    let newLayOutData = layoutData.filter((item)=>{
      return item.i != checkItem
    })
    setLayoutData(newLayOutData)
    setCheckItem('')
  }
  const handleCancel = () => {
    setOpen(false);
  }

  const content = (val,index)=>{
    return(
      <div className="btn-list">
        {
          val.oprates && val.oprates.length>0 &&
          val.oprates.map((item)=>{
              switch (item) {
                case 'del':
                  return (
                    <div key={item} className="oprateItem" onClick={(e)=>{e.stopPropagation(); onRemoveItem(e,val,index)}}>
                      <DeleteOutlined /><span>删除</span>
                    </div>
                  )
                case 'sd':
                  if(val.static){
                    return (
                      <div key={item} className="oprateItem" onClick={(e)=>{e.stopPropagation(); unLockItem(e,val,index)}}>
                        <UnlockOutlined /><span>解锁</span>
                      </div>
                    )
                  }else{
                    return (
                      <div key={item} className="oprateItem" onClick={(e)=>{e.stopPropagation(); lockItem(e,val,index)}}>
                        <LockOutlined /><span>锁定</span>
                      </div>
                    )
                  }
                default:
              }
          })
        }
      </div>
    )
  }

  const createWidget = (val: DashboardWidgetInfo,index) => {
    const removeStyle = {
      position: "relative",
      right: "2px",
      top: 0,
      cursor: "pointer",
      zIndex:'999',
    };
    const i = val.i;
    return (
      <div key={val.i}
           data-grid={{ ...val }}
           onMouseEnter={(e)=>{onMousEenter(e,val)}}
           onMouseLeave={(e)=>{onMouseLeave(e,val)}}
           className={["dashboardWidget",checkItem==val.i?'checked':'']}
      >
        <div
          className="wHeader"
          style={removeStyle}
        >
          <div className="titleItem">{val.i}</div>
          <Popover placement="left" content={() => content(val,index)}>
            <div className='three_dot' >
              <MoreOutlined style={{ fontSize: '22px', color: '#547BEB' }} />
            </div>
          </Popover>
        </div>

        { val?.chartType == 'bar'?
            <div className="spcInfo"><React.Suspense fallback={'loading'}><BarChartLazy /></React.Suspense></div>
            :
            <div className="spcInfo"><React.Suspense fallback={'loading'}><PieChartLazy /></React.Suspense></div>
        }
      </div>
    );
  }

  const onLayoutChange = (layouts: any[]) => {
    store.dispatch(renewPosition(layouts));
  };

  return (
    <div className="Dashboard" style={{height:pageHeight+'px'}}>
        <ResponsiveReactGridLayout
          className="layout"
          rowHeight={160}
          breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
          margin={{ lg: [10, 10], md: [10, 10], sm: [10, 10], xs: [5, 5] }}
          onLayoutChange={onLayoutChange}
        >
          {layoutData?.map((item,index) => createWidget(item,index))}
        </ResponsiveReactGridLayout>
      <Modal
        title="Title"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <p>确定要删除此条数据吗？</p>
      </Modal>
    </div>
  );
}

export default Dashboard;
